package main

import (
	"context"
	"earn/persistence"
	"time"
)

var (
	futuresInfoMap map[string][]*persistence.FuturesInfo
)

func futures_init() {
	futuresInfoMap = make(map[string][]*persistence.FuturesInfo)
	InitFuturesInfoList()
	GetFuturesInfoList()
	ticker := time.NewTicker(time.Hour)
	// 每一小时读取一下合约数据，防止新上
	go func() {
		for {
			<-ticker.C
			futuresInfoMap = make(map[string][]*persistence.FuturesInfo)
			InitFuturesInfoList()
			GetFuturesInfoList()
		}
	}()
}

func InitFuturesInfoList() {
	infos, err := spiderClient.NewOKEXGetFuturesInstrumentsService().Do(context.Background())
	if err == nil {
		for _, info := range infos {
			if info.QuoteCurrency == "USDT" {
				err = ppersistence.InsertFuturesInfo(&persistence.FuturesInfo{Coin: info.BaseCurrency, System: "okex"})
				if err != nil {
					Error.Println(err)
				}
			}
		}
	}

	exchangeInfos, err := binanceClient.NewExchangeInfoService().Do(context.Background())
	if err == nil {
		for _, exchangeInfo := range exchangeInfos.Symbols {
			if exchangeInfo.QuoteAsset == "USDT" {
				err = ppersistence.InsertFuturesInfo(&persistence.FuturesInfo{Coin: exchangeInfo.BaseAsset, System: "binance"})
				if err != nil {
					Error.Println(err)
				}
			}
		}
	}
}

func GetFuturesInfoList() {
	fInfos, err := ppersistence.GetFuturesInfoList()
	if err != nil {
		Error.Println(err)
		return
	}
	for _, fInfo := range fInfos {
		if _, bOK := futuresInfoMap[fInfo.Coin]; !bOK {
			futuresInfoMap[fInfo.Coin] = make([]*persistence.FuturesInfo, 0)
		}
		futuresInfoMap[fInfo.Coin] = append(futuresInfoMap[fInfo.Coin], fInfo)
	}
}

func CheckFuturesInfo(coin string) bool {
	if fInfos, bOK := futuresInfoMap[coin]; bOK && len(fInfos) > 0 {
		return true
	}

	return false

	//暂时不去网站中读取
	/*
		bHasOne := false
		_, err := spiderClient.NewOKEXGetFuturesMarkPriceService().BaseCurrency(coin).Do(context.Background())
		if err == nil {
			bHasOne = true
			err = ppersistence.InsertFuturesInfo(&persistence.FuturesInfo{Coin: coin, System: "okex"})
			if err != nil {
				Error.Println(err)
			}
		}
		_, err = binanceClient.NewListPricesService().Symbol(fmt.Sprintf("%sUSDT", coin)).Do(context.Background())
		if err == nil {
			bHasOne = true
			err = ppersistence.InsertFuturesInfo(&persistence.FuturesInfo{Coin: coin, System: "binance"})
			if err != nil {
				Error.Println(err)
			}
		}
		return bHasOne
	*/
}
